<template>
  <el-dialog
    :title="showTitle"
    :visible="dialogVisible"
    @close="closeDialog"
  >
    <el-form ref="formRef" label-width="120px" :rules="rules" :model="ruleForm">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model.trim="ruleForm.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model.trim="ruleForm.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="ruleForm.manager" style="width:80%" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model.trim="ruleForm.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <div slot="footer">
      <el-button type="primary" size="small" @click="submit">确定</el-button>
      <el-button size="small" @click="closeDialog()">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { reqGetEmployeesSimple } from '@/api/employees'
import { reqAddDepartments, reqGetDepartDetails, reqEditDepartments } from '@/api/departments'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    depts: {
      type: Array,
      required: true
    },
    nodeData: {
      type: Object,
      required: true
    }
  },
  data() {
    const validateName = (rule, value, callback) => {
      // 简单版
      // 判断当前输入的名称是否在所有数据中都不重复
      // const isRepeat = this.depts.some(item => item.name === value)
      // isRepeat ? callback(new Error(`已有${value}部门编码`)) : callback()

      // 复杂版
      // console.log(this.depts.filter(item => item.pid === this.nodeData.id))
      let children = []
      if (this.ruleForm.id) {
        if (this.nodeData.name === value) {
          return callback()
        }
        children = this.depts.filter(item => item.pid === this.nodeData.pid)
      } else {
        children = this.depts.filter(item => item.pid === this.nodeData.id)
      }
      const isRepeat = children.some(item => {
        return item.name === value
      })
      isRepeat ? callback(new Error(`已有${value}部门名称`)) : callback()
    }
    const validateCode = (rule, value, callback) => {
      if (this.ruleForm.id) {
        console.log(this.nodeData.code, value)
        if (this.nodeData.code === value) {
          callback()
          return
        }
      }
      // 判断当前输入的编码是否在所有数据中都不重复
      const isRepeat = this.depts.some(item => item.code === value)
      isRepeat ? callback(new Error(`已有${value}部门编码`)) : callback()
    }
    return {
      ruleForm: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      options: [],
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: ['blur'] },
          { max: 50, message: '部门名称不能超过50个字符' },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: ['blur'] },
          { max: 50, message: '部门编码不能超过50个字符' },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur'] }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: ['blur'] },
          { max: 300, message: '部门介绍不能超过300个字符' }
        ]
      }
    }
  },
  computed: {
    showTitle() {
      return this.ruleForm.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getEmployeesSimple()
  },
  methods: {
    closeDialog() {
      // 可以实现关闭弹窗的效果，但是违反了单项数据流的原则，不允许！！！
      // dialogVisible 是父组件传过来数据，只有父组件可以修改
      //   this.dialogVisible = false
      this.$emit('update:dialogVisible', false)
      this.$refs.formRef.resetFields()
      this.ruleForm = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
    },
    async getEmployeesSimple() {
      const { data: { data }} = await reqGetEmployeesSimple()
      // console.log(data)
      this.options = data
    },
    submit() {
      // 预校验表单
      this.$refs.formRef.validate(async(boo) => {
        if (boo) {
          // console.log('校验通过', { ...this.ruleForm, pid: this.nodeData.id })
          if (this.ruleForm.id) {
            await reqEditDepartments(this.nodeData.id)
          } else {
            await reqAddDepartments({ ...this.ruleForm, pid: this.nodeData.id })
          }
          this.$message.success(this.showTitle + '成功')
          this.$emit('add-depts')
          this.closeDialog()
        } else {
          console.log('校验不通过')
        }
      })
    },
    async getDepartDetails(id) {
      const { data: { data }} = await reqGetDepartDetails(id)
      console.log(data)
      this.ruleForm = data
    }
  }
}
</script>

<style>

</style>
